#include "Text.h"
#include "rgb.h"
#include "gmemory.h"
#include "direct2d_1.h"


Text::Text() {
    // m_PreShowRect = this;
    m_FontSize = 16;
    m_color = COLOR::WHITE;

    m_bitmap_dirty = m_layout_dirty = false;
}


void Text::setFont(int font_size) {
	m_FontSize = font_size;
	layoutDirty();
	bitmapDirty();
}


void Text::SetColor(uint color) {
	m_color = color;
	bitmapDirty();
}


void Text::Lock(int Width) {
	m_Lock = Width;
	layoutDirty();
	bitmapDirty();
}



void Text::SetString(const std::wstring& wstr) {
	m_WStr = wstr;
	layoutDirty();
	updateLayout();
	bitmapDirty();
}



void Text::layoutDirty() {
	m_layout_dirty = true;
}

void Text::updateLayout() {
	if (!m_layout_dirty) {
		return;
	}
	m_layout_dirty = false;

	m_Width = 0;
	m_Height = m_FontSize;
	if (m_WStr.empty()) {
		return;
	}

	auto m_pFormat = LabelManager::getInstace()->getFormat(m_FontSize);
	IDWriteTextLayout* m_pLayout = nullptr;
	LabelManager::toLayout(m_pFormat, m_Lock, m_WStr.c_str(), m_WStr.length(), m_pLayout);
	LabelManager::toSize(m_pLayout, m_Width, m_Height);

	if (m_pLayout) {
		m_pLayout->Release();
	}
}


void Text::bitmapDirty() {
	m_bitmap_dirty = true;
}


void Text::updateBitmap() {
	if (!m_bitmap_dirty) {
		return;
	}
	m_bitmap_dirty = false;

	auto m_pFormat = LabelManager::getInstace()->getFormat(m_FontSize);
    auto m_pBrush = LabelManager::getInstace()->getBrush(m_color);
	IDWriteTextLayout* m_pLayout = nullptr;
	LabelManager::toLayout(m_pFormat, m_Lock, m_WStr.c_str(), m_WStr.length(), m_pLayout);
    m_bitmap.load(m_pLayout, m_pBrush, nullptr);
}



void Text::render(int maper_x, int maper_y) {
	updateLayout();
	updateBitmap();
	if (m_bitmap.isValid()) {
		m_bitmap.render(m_x - maper_x, m_y - maper_y);
	}
}
